//
//  NSDictionary+Tools.m
//  MiaoPai
//
//  Created by jiaxuzhou on 2017/6/10.
//  Copyright © 2017年 Jeakin. All rights reserved.
//
//


#import "NSDictionary+Tools.h"
#import "NSString+Tools.h"
#import <Foundation/Foundation.h>

@implementation NSDictionary (Tools)

- (NSString *)mp_buildHttpQueryString
{
    NSMutableArray * pairs = [NSMutableArray array];
    [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        key = [[NSString stringWithFormat:@"%@",key] urlEncode];
        
        if ([obj isKindOfClass:[NSDictionary class]]) {
            [obj enumerateKeysAndObjectsUsingBlock:^(id k, id o, BOOL *stop) {
                k = [[NSString stringWithFormat:@"%@",k] urlEncode];
                o = [[NSString stringWithFormat:@"%@",o] urlEncode];
                
                [pairs addObject:[NSString stringWithFormat:@"%@[%@]=%@", key, k, o]];
            }];
        }  else if ([obj isKindOfClass:[NSArray class]]) {
            [obj enumerateObjectsUsingBlock:^(id no, NSUInteger idx, BOOL *stop) {
                no = [[NSString stringWithFormat:@"%@",no] urlEncode];
                [pairs addObject:[NSString stringWithFormat:@"%@[]=%@", key, no]];
                
            }];
        } else {
            obj = [[NSString stringWithFormat:@"%@",obj] urlEncode];
            [pairs addObject:[NSString stringWithFormat:@"%@=%@", key, obj]];
        }
        
    }];
    return [pairs componentsJoinedByString:@"&"];
}

id mp_getValidObjectFromDictionary(NSDictionary *dic, id key)
{
    if (MPT_Dic_Is_Valid(dic) && MPT_Object_Is_Valid(key) && [key conformsToProtocol:@protocol(NSCopying)])
    {
        return dic[key];
    }
    
    return nil;
}


@end
